﻿using System;
using System.IO;

namespace kill1C.Utils
{
    static class Log
    {
        public static string LogDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + @"\kill1C\Logs\";

        public static string LogPath
        {
            get
            {
                return LogDir + DateTime.Now.ToShortDateString() + "_PID_" + AppProc.PID + "_USER_" + Environment.UserName + ".txt";
            }
        }

        public static void Write(string message)
        {
            try
            {
                CheckLogDir();
                CheckLogFile(LogPath);

                string s = "";
                if (!char.IsPunctuation(message[message.Length - 1]))
                {
                    s = ".";
                }

                File.AppendAllText(LogPath, DateTime.Now.ToString() + "  " + message + s + Environment.NewLine);
            }
            catch { }
        }

        private static void CheckLogDir()
        {
            if (!Directory.Exists(LogDir))
            {
                Directory.CreateDirectory(LogDir);
            }

            //Удаляем лог файлы которые старше 2 дней
            string[] logFiles = Directory.GetFiles(LogDir);
            DateTime minDate = DateTime.Now.AddDays(-2);

            foreach (string logFile in logFiles)
            {
                if (File.GetCreationTime(logFile) < minDate || File.GetLastWriteTime(logFile) < minDate)
                    File.Delete(logFile);
            }
        }

        private static void CheckLogFile(string logPath)
        {
            try
            {                
                FileInfo f = new FileInfo(logPath);
                if ((f.Length / 1024f) / 1024f > 1f)
                {
                    //Удаляем лог файл если он больше 1MB
                    f.Delete();
                }                
            }
            catch { }
        }
    }
}
